
let messageTypeDoc  = {
    
    "message_type":"function"
};

const config = {
};


var containers = {
    audio: true,
    video: {
        width: 320,
        height: 360,
    },
}

planWebsocket = null

var room = {
    
    roomId: "",
    userId: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substring(0,7),
    localRtc: null,
    remoteRtcs: {},
}

messageTypeDoc["join_res"] = JoinRes;
messageTypeDoc["join_broadcast"] = JoinBroadcast;
messageTypeDoc["left_broadcast"] = LeftBroadcast;
messageTypeDoc["publish_res"] = PublishResult
messageTypeDoc["heart"] = Heart
messageTypeDoc["subscribe_res"] = SubscribeRes;
messageTypeDoc["user_list"] = UserLeft;

function StartServer() {

    roomObj = document.getElementById("roomId");
    room.roomId = roomObj.value;
    if (room.roomId == "") {

        return;
    }
    if('WebSocket' in window){
        
        planWebsocket = new WebSocket('ws://127.0.0.1:300/');

        planWebsocket.onopen = function(event){

            console.log("websocket connected");
            // send join message to server
            SendJoinMessage();
        }
        
        planWebsocket.onmessage = function(event){

            processMessage(event);
        }

        planWebsocket.onclose = function(event){

            console.log("websocket disconnect");
        }

        planWebsocket.onerror = function(event){

            alert("websocket通信发生错误");	
        }

    }else{

        alert("此浏览器本网站暂时不支持");
    }
}

function processMessage(event) {

    // add try/catach
    var messageDoc = JSON.parse(event.data);
    console.log(event.data);
    if (messageTypeDoc[messageDoc.type] != null) {
        messageTypeDoc[messageDoc.type](messageDoc);
    }
}

function SendMessage(str) {

    planWebsocket.send(str);
}

function SendJoinMessage() {

    let joinMsg = {

        "user_id":room.userId,
        "type":"join",
        "token":"number",
        "room_id": room.roomId,
    }
    SendMessage(JSON.stringify(joinMsg));
}

async function JoinRes(input) {

    console.log(input);
    let publish = {

        "type":"publish",
        "user_id":room.userId,
        "room_id":room.roomId,
        "sdp":""
    }
    document.getElementById("enterRoom").disabled = true

    room.localRtc = new RTCPeerConnection(null)

    var stream = await navigator.mediaDevices.getUserMedia(containers)

    room.localRtc.addStream(stream);
    localVideo = document.getElementById('localVideo')
    localVideo.srcObject = stream
    localVideo.play();

    var offer = await room.localRtc.createOffer()
    await room.localRtc.setLocalDescription(offer);
    
    publish["sdp"] = offer.sdp;
    
    SendMessage(JSON.stringify(publish));
}

function Heart(message) {

    let heart = {
        "code":0,
        "type":"heart",
        "room_id":room.roomId,
        "user_id":room.userId,
    }
    SendMessage(JSON.stringify(heart));
}

function PublishResult(message) {

    if (message.code != 0) {

        alert("推流失败");
        return;
    } 
    room.localRtc.setRemoteDescription({
        type:'answer',
        sdp:message.sdp
    });
}

async function LeftBroadcast(message) {

    if (message.user_id == room.userId) {

        planWebsocket.close();
        return
    }
    if (room.remoteRtcs[message.user_id] != null) {

        room.remoteRtcs[message.user_id].close();
        room.remoteRtcs[message.user_id] = null
        for (var index = 0; index < 4; index++) {

            video = document.getElementById(index.toString(10));
            if (video.value == message.user_id) {

                console.log(message.user_id, video.value);
                video.value = "";
                video.srcObject = null;
            }
        }

    }
}

async function JoinBroadcast(message) {

    if (message.user_id == room.userId) {
        return;
    }
    size = room.remoteRtcs.length;
    if (size >= 4) {

        return;
    }
    let subscribe = {

        "room_id":room.roomId,
        "user_id":room.userId,
        "sub_user_id":message.user_id,
        "type":"subscribe",
        "sdp":""
    }
    room.remoteRtcs[message.user_id] = new RTCPeerConnection(null);

    var optional =  {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
    };
    room.remoteRtcs[message.user_id].addTransceiver("audio", {direction: "recvonly"});
    room.remoteRtcs[message.user_id].addTransceiver("video", {direction: "recvonly"});
    var offer = await room.remoteRtcs[message.user_id].createOffer(optional)
    room.remoteRtcs[message.user_id].setLocalDescription(offer);
    subscribe["sdp"] = offer.sdp;
    SendMessage(JSON.stringify(subscribe));
}

function SubscribeRes(message) {

    if (message.code != 0) {

        return;
    }
    console.log("set answer");
    room.remoteRtcs[message.sub_user_id].addEventListener('addstream', function(event){

        for (var index = 0; index < 4; index++) {

            video = document.getElementById(index.toString(10));
            if (video.srcObject == null) {

                console.log(event);
                video.srcObject = event.stream;
                video.value = message.sub_user_id;
                console.log(video.value)
                video.play();        
                break;
            }
        }
    });
    room.remoteRtcs[message.sub_user_id].setRemoteDescription(

        {type: 'answer', sdp:message.sdp}
    );
}

async function UserLeft(message) {

    if (message.user_list == null) {

        return;
    }
    for (var index = 0; index < message.user_list.length; index++) {

        if (room.remoteRtcs[message.user_list[index]] != null) {

            continue;
        }
        console.log(message.user_list[index]);
        let subscribe = {

            "room_id":room.roomId,
            "user_id":room.userId,
            "sub_user_id":message.user_list[index],
            "type":"subscribe",
            "sdp":""
        }
        room.remoteRtcs[message.user_list[index]] = new RTCPeerConnection(null);
        var optional =  {
            offerToReceiveAudio: 1,
            offerToReceiveVideo: 1,
        };
        room.remoteRtcs[message.user_list[index]].addTransceiver("audio", {direction: "recvonly"});
        room.remoteRtcs[message.user_list[index]].addTransceiver("video", {direction: "recvonly"});
        var offer = await room.remoteRtcs[message.user_list[index]].createOffer(optional)
        room.remoteRtcs[message.user_list[index]].setLocalDescription(offer);
        subscribe["sdp"] = offer.sdp;
        SendMessage(JSON.stringify(subscribe));
    }
}
